package cn.tedu.mall.producer.service.impl;

import cn.tedu.mall.producer.ex.ServiceException;
import cn.tedu.mall.producer.mapper.AttributeMapper;
import cn.tedu.mall.producer.pojo.dto.AttributeAddNewDTO;
import cn.tedu.mall.producer.pojo.entity.Attribute;
import cn.tedu.mall.producer.pojo.vo.AttributeDetailVO;
import cn.tedu.mall.producer.pojo.vo.AttributeListItemVO;
import cn.tedu.mall.producer.service.IAttributeService;
import cn.tedu.mall.producer.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class AttributeServiceImpl implements IAttributeService {
    @Autowired
    private AttributeMapper attributeMapper;

    @Override
    public void addNew(AttributeAddNewDTO attributeAddNewDTO) {
        Attribute attribute = new Attribute();
        BeanUtils.copyProperties(attributeAddNewDTO, attribute);

        int insert = attributeMapper.insert(attribute);
        if (insert != 1) {
            String message = "添加属性失败,服务器忙，";
            log.error(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
    }

    @Override
    public void deleteById(Long id) {
        AttributeDetailVO attributeDetailVO = attributeMapper.getById(id);
        if (attributeDetailVO == null) {
            String message = "删除属性失败，尝试删除的数据（id=" + id + "）不存在！";
            log.error(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        int count = attributeMapper.deleteById(id);
        if (count != 1) {
            String message = "删除属性失败，服务器忙，请稍后再次尝试！";
            log.error(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
    }

    @Override
    public List<AttributeListItemVO> list() {
        return attributeMapper.list();
    }
}
